'use client';
import React, { useState, useEffect } from 'react';
import { Table, Button, Tag, Modal, Image, Tooltip, Space, Input, Select, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { SearchOutlined } from '@ant-design/icons';
import { articleService } from '@/service/article.service';
import parse from 'html-react-parser';

// 文章状态常量
const ARTICLE_STATUS = {
  STATUS_PENDING: -1, // 待审核
  STATUS_REJECTED: 0, // 审核失败 / 删除
  STATUS_APPROVED: 1, // 审核成功
};

// 文章状态映射
const statusMap = {
  [ARTICLE_STATUS.STATUS_PENDING]: { text: '待审核', color: 'warning' },
  [ARTICLE_STATUS.STATUS_REJECTED]: { text: '审核失败', color: 'error' },
  [ARTICLE_STATUS.STATUS_APPROVED]: { text: '审核成功', color: 'success' },
};

// 用户信息接口
interface UserInfo {
  id: number;
  username: string;
  avatar: string;
  email: string;
}

// 文章接口定义
export interface Article {
  id: number;
  title: string;
  content: string;
  coverImage: string | null;
  viewCount: number;
  likeCount: number;
  commentCount: number;
  isActive: number;
  authorId: number | null;
  categoryId: number | null;
  createdAt: Date;
  updatedAt: Date;
  tags: Array<{ id: number; name: string }>;
  author?: UserInfo; // 作者信息
}


const ArticleList: React.FC = () => {
  const [articles, setArticles] = useState<Article[]>([]);
  const [filteredArticles, setFilteredArticles] = useState<Article[]>([]);
  const [selectedArticle, setSelectedArticle] = useState<Article | null>(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState<number | null>(null);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);

  // 加载文章数据
  const loadArticles = async (page: number = currentPage, size: number = pageSize, keyword: string = searchText, isActive: number | null = statusFilter) => {
    setLoading(true);
    try {
      // 调用后端API获取数据
      const response = await articleService.getArticleList({
        page,
        pageSize: size,
        keyword: keyword || undefined,
        isActive: isActive !== null ? isActive : null // -1表示不过滤状态
      });
      
      console.log('文章列表响应:', response);
      
      // 根据实际API响应格式调整
      const articlesData = response.data || [];
      const totalCount = response.total || 0;
      
      setArticles(articlesData as []);
      setFilteredArticles(articlesData as []);
      setTotal(totalCount);
      
    } catch (error: unknown) {
      console.error('加载文章失败:', error);
      // 出错时清空数据
      setArticles([]);
      setFilteredArticles([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  };

  // 搜索和过滤文章
  const handleSearch = () => {
    // 重新加载数据，应用搜索和过滤条件
    loadArticles(1, pageSize, searchText, statusFilter);
    setCurrentPage(1);
  };

  // 重置搜索条件
  const handleReset = () => {
    setSearchText('');
    setStatusFilter(null);
    setCurrentPage(1);
    // 重新加载所有数据
    loadArticles(1, pageSize, '', null);
  };

  // 查看文章详情
  const handleViewArticle = (article: Article) => {
    setSelectedArticle(article);
    setModalVisible(true);
  };

  // 表格列定义
  const columns: ColumnsType<Article> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 60,
      fixed: 'left',
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true,
      render: (text: string, record: Article) => (
        <Tooltip title={text}>
          <a onClick={() => handleViewArticle(record)}>{text}</a>
        </Tooltip>
      ),
    },
    {
      title: '内容',
      dataIndex: 'content',
      key: 'content',
      ellipsis: true,
      render: (text: string, record: Article) => {
         // 使用useMemo优化性能，避免每次渲染都执行正则表达式
         const plainText = React.useMemo(() => text.replace(/<[^>]*>/g, ''), [text]);
         
         return (
           <Tooltip title={parse(text)}>
            <span>
               {plainText.length > 50 ? `${plainText.substring(0, 50)}...` : plainText}
               {plainText.length > 50 && (
                 <a 
                  onClick={(e) => {
                     e.stopPropagation();
                     handleViewArticle(record);
                   }}
                   style={{ marginLeft: '4px', color: '#1890ff' }}
                 >
                   查看全部
                 </a>
               )}
             </span>
           </Tooltip>
         );
       },
    },
    {
      title: '封面图',
      dataIndex: 'coverImage',
      key: 'coverImage',
      width: 120,
      render: (coverImage: string | null) => {
        if (!coverImage) {
          return <Tag color="default">无封面</Tag>;
        }
        return (
          <Image
            width={100}
            height={60}
            src={coverImage}
            alt="封面图"
            preview={false}
            style={{ objectFit: 'cover' }}
          />
        );
      },
    },
    {
      title: '点击数',
      dataIndex: 'viewCount',
      key: 'viewCount',
      width: 80,
      align: 'center',
    },
    {
      title: '喜欢数',
      dataIndex: 'likeCount',
      key: 'likeCount',
      width: 80,
      align: 'center',
    },
    {
      title: '评论数',
      dataIndex: 'commentCount',
      key: 'commentCount',
      width: 80,
      align: 'center',
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
      width: 120,
      align: 'center',
      render: (author: UserInfo | undefined) => {
        if (!author) {
          return <Tag color="default">未知</Tag>;
        }
        return (
          <Tooltip 
            title={
              <div>
                <div><strong>ID:</strong> {author.id}</div>
                <div><strong>用户名:</strong> {author.username}</div>
                <div><strong>邮箱:</strong> {author.email}</div>
                <div><img src={author.avatar} alt="头像" style={{width: '40px', height: '40px', borderRadius: '50%', marginTop: '5px'}} /></div>
              </div>
            }
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <img 
                src={author.avatar} 
                alt={author.username}
                style={{ 
                  width: '24px', 
                  height: '24px', 
                  borderRadius: '50%',
                  objectFit: 'cover' 
                }}
              />
              <span>{author.username}</span>
            </div>
          </Tooltip>
        );
      },
    },
    {
      title: '分类ID',
      dataIndex: 'categoryId',
      key: 'categoryId',
      width: 80,
      align: 'center',
      render: (categoryId: number | null) => categoryId || <Tag color="default">未分类</Tag>,
    },
    {
      title: '状态',
      dataIndex: 'isActive',
      key: 'isActive',
      width: 100,
      align: 'center',
      render: (status: number) => {
        const statusInfo = statusMap[status] || { text: '未知', color: 'default' };
        return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 160,
      render: (createdAt: Date) => new Date(createdAt).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right',
      render: (_: any, record: Article) => (
        <Space size="middle">
          <Button 
            size="small" 
            type="link" 
            onClick={() => handleViewArticle(record)}
          >
            查看
          </Button>
        </Space>
      ),
    },
  ];

  // 页面加载时获取数据
  useEffect(() => {
    loadArticles();
  }, []);

  // 分页变化时重新加载数据
  const handlePageChange = (page: number, size?: number) => {
    const newPageSize = size || pageSize;
    setCurrentPage(page);
    setPageSize(newPageSize);
    loadArticles(page, newPageSize, searchText, statusFilter);
  };

  return (
    <div style={{ padding: '20px' }}>
      <div style={{ marginBottom: '20px', display: 'flex', gap: '10px', alignItems: 'flex-end' }}>
        <h1 style={{ margin: 0 }}>文章管理</h1>
       
      </div>
      
      {/* 搜索和过滤区域 */}
      <div style={{ 
        marginBottom: '20px', 
        padding: '16px', 
        backgroundColor: '#f5f5f5', 
        borderRadius: '6px',
        display: 'flex',
        gap: '16px',
        flexWrap: 'wrap'
      }}>
        <Input
          placeholder="搜索文章标题"
          prefix={<SearchOutlined />}
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          onPressEnter={handleSearch}
          style={{ width: 300 }}
        />
        
        <Select
          placeholder="按状态过滤"
          value={statusFilter}
          onChange={setStatusFilter}
          allowClear
          style={{ width: 150 }}
          options={[
            { value: -1, label: '待审核' },
            { value: 0, label: '审核失败' },
            { value: 1, label: '审核成功' },
          ]}
        />
        
        <Button type="primary" onClick={handleSearch}>
          搜索
        </Button>
        
        <Button onClick={handleReset}>
          重置
        </Button>
      </div>
      
      {/* 文章表格 */}
      <Table
        columns={columns}
        dataSource={filteredArticles}
        rowKey="id"
        loading={loading}
        pagination={{
          current: currentPage,
          pageSize: pageSize,
          total: total,
          onChange: handlePageChange,
          onShowSizeChange: handlePageChange,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条数据`,
        }}
        scroll={{ x: 'max-content' }}
        style={{ marginBottom: '20px' }}
      />
      
      {/* 文章详情模态框 */}
      <Modal
        title="文章详情"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={800}
        destroyOnHidden={true}
      >
        {selectedArticle && (
          <div>
            <h2>{selectedArticle.title}</h2>
            
            <div style={{ marginBottom: '20px', display: 'flex', gap: '20px', flexWrap: 'wrap' }}>
              <div>
                <strong>ID:</strong> {selectedArticle.id}
              </div>
              <div>
                <strong>作者ID:</strong> {selectedArticle.authorId || '未知'}
              </div>
              <div>
                <strong>分类ID:</strong> {selectedArticle.categoryId || '未分类'}
              </div>
              <div>
                <strong>状态:</strong> <Tag color={statusMap[selectedArticle.isActive].color}>
                  {statusMap[selectedArticle.isActive].text}
                </Tag>
              </div>
              <div>
                <strong>点击数:</strong> {selectedArticle.viewCount}
              </div>
              <div>
                <strong>喜欢数:</strong> {selectedArticle.likeCount}
              </div>
              <div>
                <strong>评论数:</strong> {selectedArticle.commentCount}
              </div>
              <div>
                <strong>创建时间:</strong> {new Date(selectedArticle.createdAt).toLocaleString()}
              </div>
              <div>
                <strong>更新时间:</strong> {new Date(selectedArticle.updatedAt).toLocaleString()}
              </div>
            </div>
            
            {selectedArticle.coverImage && (
              <div style={{ marginBottom: '20px', textAlign: 'center' }}>
                <Image
                  width={600}
                  src={selectedArticle.coverImage}
                  alt="封面图"
                  preview={true}
                  style={{ borderRadius: '4px' }}
                  
                />
              </div>
            )}
            
            <div style={{ marginBottom: '20px' }}>
              <strong>标签:</strong>
              <Space size="small" style={{ marginLeft: '10px' }}>
                {selectedArticle.tags.map(tag => (
                  <Tag key={tag.id} color="blue">
                    {tag.name}
                  </Tag>
                ))}
              </Space>
            </div>
            
            <div>
              <strong>内容:</strong>
              <div style={{ 
                marginTop: '10px', 
                padding: '10px', 
                border: '1px solid #e8e8e8', 
                borderRadius: '4px',
                wordBreak: 'break-all',
                lineHeight: '1.6'
              }}>
                {parse(selectedArticle.content)}
              </div>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default ArticleList;
